/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.luxoft.corporate.blog.ui;

import com.luxoft.corporate.blog.db.entities.Topic;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;

/**
 *
 * @author Egor
 */
public class TopicCombobox extends JComboBox<Topic> {

    private TopicComboboxModel comboboxModel;

    public TopicCombobox() {
        comboboxModel = new TopicComboboxModel();
        init();
    }

    private void init() {
        setModel(comboboxModel);
    }

    public void setData(List<Topic> topics) {
        comboboxModel.setTopics(topics);
    }

    private static class TopicComboboxModel extends DefaultComboBoxModel<Topic> {

        private List<Topic> topics;
        private int selectedIndex;
        private Topic selectedTopic;

        public TopicComboboxModel() {
            topics = new ArrayList<>();
        }

        public TopicComboboxModel(List<Topic> topics) {
            this.topics = topics;
        }

        public void setTopics(List<Topic> topics) {
            this.topics = topics;
            fireIntervalAdded(this, 0, topics.size());
        }

        @Override
        public void setSelectedItem(Object anObject) {
            for (int i = 0; i < topics.size(); i++) {
                if (topics.get(i).equals(anObject)) {
                    selectedIndex = i;
                    selectedTopic = (Topic) anObject;
                }
            }

        }

        public Topic getSelectedTopic() {
            return topics.get(selectedIndex);

        }

        @Override
        public Object getSelectedItem() {
            return selectedTopic;
        }

    }

}
